package zack.project.infrastructure.gateway;

import zack.project.trigger.api.IRebateService;
import zack.project.trigger.api.dto.RebateBehaviorDTO;
import zack.project.trigger.api.request.Request;
import zack.project.trigger.api.response.Response;
import zack.project.types.enums.NotifyTaskHTTPEnumVO;
import zack.project.types.enums.ResponseCode;
import zack.project.types.exception.AppException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author A1793
 */
@Service
@Slf4j
public class RebateRpcService {

    @Reference(version = "1.0",
            check = false,
            mock = "return \" RemoteService:rebate not available right now.\"")
    IRebateService rebateService;

    public String sendRebate(String notifyInterface, String parameterJson) {
        try {
            Map<String, Object> parameterMap = JSON.parseObject(parameterJson, new TypeReference<HashMap<String, Object>>() {
            });
            String behaviorType = (String) parameterMap.get("behaviorType");
            String userId = (String) parameterMap.get("userId");
            String outTradeNo = (String) parameterMap.get("outTradeNo");


                Request<RebateBehaviorDTO> request = Request.<RebateBehaviorDTO>builder()
                        .appId("group" + userId).
                        appToken("group" + userId)
                        .data(RebateBehaviorDTO.builder()
                                .userId(userId)
                                .outTradeNo(outTradeNo)
                                .behaviorType(behaviorType)
                                .build()
                        ).build();
                Response response = rebateService.sendRebate(request);
                if (response.getData().equals("false")) {
                    return NotifyTaskHTTPEnumVO.ERROR.getCode();
                }

            return NotifyTaskHTTPEnumVO.SUCCESS.getCode();
        } catch (Exception e) {
            log.error("拼团回调 RPC 接口服务异常{}", notifyInterface, e);
            throw new AppException(ResponseCode.RPC_EXCEPTION);
        }

    }

}
